package com.sdy.mvc.feign;

import com.sdy.mvc.utils.JsonUtil;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Base64;

/**
 * @author zhouziqiang
 */
@Slf4j
public class FeignSpringBodyDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        try (InputStream is = response.body().asInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int n;
            while (-1 != (n = is.read(buffer))) {
                output.write(buffer, 0, n);
            }
            byte[] data = output.toByteArray();
            com.sdy.common.model.Response result;
            try {
                result = JsonUtil.deserialize(Base64.getDecoder().decode(data), com.sdy.common.model.Response.class);
            } catch (Exception e) {
                log.error("FeignSpringBodyDecoder deserialize error![{}]", e.getMessage());
                throw e;
            }
            return result.getData();
        }
    }
}